package Bill.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
 
import java.io.InputStreamReader;
import java.util.StringTokenizer;

import javax.naming.ConfigurationException;

public class Configuration {
 public static  int Config_portServeurGroup;
 public static int Config_portServeur;
  
 public static boolean loadConfiguration(){
	 return Configuration.loadConfiguration(new File("portsecoute.conf"));
 }
 public static boolean loadConfiguration(String f){
	 return Configuration.loadConfiguration(new File(f));
 }
	 public static boolean loadConfiguration(File f){
		 String ligne = null;
		 try {
			BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(f)));
			
			StringTokenizer t;
			 boolean Config_portServeurGroup_IS_SET=false,
					 Config_portServeur_IS_SET=false;
			while(null!=(ligne=br.readLine())){
				if(!(null==ligne||ligne.trim().startsWith("#")||ligne.trim()=="")){
					ligne=ligne.trim();
					 t=new StringTokenizer(ligne);
					 if(t.countTokens()>=2){
						 String key=t.nextToken();
						 ligne=t.nextToken();
						 if(key.trim().compareTo("Config_portServeurGroup")==0){
								
							 Configuration.Config_portServeurGroup=Integer.parseInt(ligne.trim());
							 Config_portServeurGroup_IS_SET=true;
							 
						}
						else if(key.trim().compareTo("Config_portServeur")==0){
							 Configuration.Config_portServeur=Integer.parseInt(ligne.trim());
							  
							 Config_portServeur_IS_SET=true;
						}
						
				
					 }
							 
					
				}
			}
			if(!Config_portServeur_IS_SET||!Config_portServeurGroup_IS_SET) throw new ConfigurationException("Malformed configuration File");
			return true;
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			System.err.println("Configuraton File not found");
			return false;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			if(e instanceof NumberFormatException)
				try {
					throw new ConfigurationException("num port is not a number["+ligne+"]");
				} catch (ConfigurationException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			System.err.println("malformed configuration File["+f.getAbsolutePath()+"]");
			return false;
		}
	 }

}
